import React, { useContext, useState } from 'react'
import classes from './CartDetails.module.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTrashCan } from '@fortawesome/free-solid-svg-icons'

import CartContext from '../../../store/cart-context'

import Backdrop from '../../UI/Backdrop/Backdrop'
import Meal from '../../Meals/Meal/Meal'
import Confirm from '../../UI/Confirm/Confirm'

const CartDetails = () => {
	const cartCtx = useContext(CartContext);

	const [showConfirm, setShowConfirm] = useState(false)

	const clearCartHandler = () => {
		setShowConfirm(true)
	}

	const cancelHandler = (e) => {
		e.stopPropagation()
		setShowConfirm(false)
	}

	const confirmHandler = () => {
		cartCtx.cartDispatch({ type: 'CLEAR_CART' }); // 清空购物车
		setShowConfirm(false)
	}

	return (
		<Backdrop>
			{
				showConfirm
				&&
				<Confirm
					onCancel={cancelHandler}
					onConfirm={confirmHandler}
					confirmText={'Are you sure clean the cart?'}
				/>
			}
			<div
				className={classes.CartDetailsBox}
				onClick={e => e.stopPropagation()}
			>
				<header className={classes.Header}>
					<h2 className={classes.Title}>Cart Details</h2>
					<div
						className={classes.ClearCart}
						onClick={clearCartHandler}
					>
						<FontAwesomeIcon icon={faTrashCan} className={classes.ClearIcon} />
						<span>Clear Cart</span>
					</div>
				</header>
				<div className={classes.MealList}>
					{
						cartCtx.items.map((meal) => {
							return (
								<Meal meal={meal} key={meal.id} isDescDisplayed={false} isCheckoutList={false} />
							)
						})
					}
				</div>
			</div>
		</Backdrop>

	)
}

export default CartDetails